package com.zhangjingcheng.yunyixia.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import com.zhangjingcheng.yunyixia.constant.MessageConstant;
import com.zhangjingcheng.yunyixia.constant.UserConstant;
import com.zhangjingcheng.yunyixia.result.Result;
import com.zhangjingcheng.yunyixia.service.impl.EmailServiceImpl;
import com.zhangjingcheng.yunyixia.util.RedisUtil;
import com.zhangjingcheng.yunyixia.util.StringUtil;
import com.zhangjingcheng.yunyixia.util.ThreadLocalUtil;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.ByteArrayOutputStream;

@RequestMapping
@RestController
@Slf4j
public class CaptchaController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private EmailServiceImpl emailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @ApiOperation("获取验证码")
    @GetMapping("/checkCode")
    public Result<String> checkCode() {
        LineCaptcha captcha = new LineCaptcha(150, 40, 4, 20);
        // 获取验证码的值
        String code = captcha.getCode().toLowerCase();
        // 生成base64图片
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        captcha.write(bos);
        String base64Image = "data:image/png;base64," + Base64.encode(bos.toByteArray());

        // 存储到Redis
        redisUtil.set(
                code,
                code,
                UserConstant.CODE_EXPIRE
        );
        return Result.success(base64Image);
    }

    /**
     * 发送邮箱验证码
     *
     * @param email     邮箱地址
     * @param checkCode 图形验证码（
     * @return 发送结果
     */
    @ApiOperation("发送邮箱验证码（需先通过图形验证码校验）")
    @GetMapping("/sendEmailCode")
    public Result<String> sendEmailCode(
            @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") String email,
            String checkCode) {
        // 1. 校验图形验证码是否有效
        if (checkCode == null || !checkCode.equals(redisUtil.get(checkCode))) {
            return Result.error(MessageConstant.CODE_ERROR);
        }

        // 2. 移除已使用的图形验证码（防止重复使用）
        redisUtil.deleteCache(ThreadLocalUtil.getId() + UserConstant.CHECK_CODE);


        // 3. 生成邮箱验证码并存储到Redis
        String emailCode = StringUtil.getRandomNumbers(UserConstant.CODE_LENGTH);
        redisUtil.set(email + UserConstant.CHECK_EMAIL_CODE, emailCode, UserConstant.CODE_EXPIRE);

        // 4. 渲染邮件模板并发送
        Context context = new Context();
        context.setVariable("code", emailCode);
        String htmlContent = templateEngine.process("EmailTemplate", context);
        emailService.sendHtml(fromEmail, email, "【云忆匣】你本次注册验证码为", htmlContent);

        return Result.success("邮箱验证码已发送，请注意查收，未找到请到垃圾邮件中寻找");
    }
}
